<script setup lang="ts">

import { Canvas, Line } from "fabric";
import { inject, ref, computed, watch, onMounted } from "vue";
import { useImageDataStore } from "@renderer/store/pinia/imageData";
const {
  viewId
} = inject('viewerInfo') as any


const imgDataStore = useImageDataStore()

const pxPermm = computed(() => {
    if (imgDataStore.extraInfoObj[viewId] && imgDataStore.extraInfoObj[viewId]['px_per_mm']){
      return imgDataStore.extraInfoObj[viewId]['px_per_mm']
    }else {
      return 0
    }
})

const pl = 20
const canvasWidth = computed(() => {
    return pxPermm.value * 100 + pl
})

const startRender = () => {
  canvasRef.value.width = canvasWidth.value ;
  console.log(`startRender, width:${canvasWidth.value}`)
  if (!canvas){
    canvasRef.value.height = 20;
    canvas = new Canvas(canvasRef.value, {});
    canvas.selection = false;
  }

  initLines();
}

watch(canvasWidth, (newVal, oldVal) => {
  if (newVal !== pl){
    startRender()
  }
})


onMounted(() => {
  if (canvasWidth.value !== pl){
    startRender()
  }
})


const containerRef = ref<any>(null);

let horizontalLine: any = null
let canvas: Canvas;
const canvasRef = ref<any>(null);

const verticalLineHeight = 3
const verticalLineHeight1 = 5
const startX = 10
const startY = 20

const initLines = () => {
  canvas.clear()
  const width = canvasWidth.value - pl;
  const verticalLineIntervalX = width / 10

  for(let i = 0; i < 11; i++){
    if (i === 0 || i === 10){
      const verticalLine = new Line([startX + i * verticalLineIntervalX, startY - verticalLineHeight1,
                                                 startX + i * verticalLineIntervalX, startY,], {
        stroke: 'red',
        strokeWidth: 3,
        selectable: false,
        hoverCursor: "default",
      });
      canvas.add(verticalLine)
    }else {
      const verticalLine = new Line([startX + i * verticalLineIntervalX,startY -  verticalLineHeight,
                                                 startX + i * verticalLineIntervalX, startY ], {
        stroke: 'red',
        strokeWidth: 2,
        selectable: false,
        hoverCursor: "default",
      });
      canvas.add(verticalLine)
    }
  }

  horizontalLine = new Line([startX, startY, startX + width, startY], {
    stroke: 'red',
    strokeWidth: 2,
    selectable: false,
    hoverCursor: "default",
  });
  canvas.add(horizontalLine)
  canvas.renderAll()
}




</script>

<template>
  <div ref="containerRef"
       class="w-full h-full flex justify-center items-end !pl-[20px]">
    <div class="inline-block">
      <canvas ref="canvasRef" class="w-full h-full"></canvas>
    </div>
    <span class="text-gray-300">10cm</span>
  </div>
</template>

<style scoped>

</style>
